import Fingerprint2 from 'fingerprintjs2'
import MobileDetect from 'mobile-detect'

/**
 * 获取设备指纹
 */
export const getFingerprintID = () => {
  return new Promise((resolve, reject) => {
    Fingerprint2.get(async function (components) {
      const values = components.map((component) => {
        return component.value
      })
      const murmur = Fingerprint2.x64hash128(values.join(''), 31)
      return resolve(murmur)
    })
  })
}

/**
 * 获取设备
 */
export const device = () => {
  let agent = navigator.userAgent
  if (agent.indexOf('Android') > -1 || agent.indexOf('Adr') > -1) {
    return 'android'
  } else if (agent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
    return 'ios'
  }
  return 'web'
}

/**
 * 获取设备信息
 */
export const getModel = () => {
  var agent = navigator.userAgent // 获取userAgent信息

  var md = new MobileDetect(agent) // 初始化mobile-detect

  // more typically we would instantiate with 'window.navigator.userAgent'
  // as user-agent; this string literal is only for better understanding

  console.log(md.mobile()) // 'Sony'
  console.log(md.phone()) // 'Sony'
  console.log(md.tablet()) // null
  console.log(md.userAgent()) // 'Safari'
  console.log(md.os()) // 'AndroidOS'
  console.log(md.is('iPhone')) // false
  console.log(md.is('bot')) // false
  console.log(md.version('Webkit')) // 534.3
  console.log(md.versionStr('Build')) // '4.1.A.0.562'
  console.log(md.match('playstation|xbox')) // false
  var os = md.os() // 获取系统
  var model = 'Unkown'
  if (os === 'iOS') { // ios系统的处理
    os = 'ios'
    model = md.mobile()
  } else if (os === 'AndroidOS') { // Android系统的处理
    os = 'android'
    var sss = agent.split(';')
    var i = sss.contains('Build/')
    if (i > -1) {
      model = sss[i].substring(0, sss[i].indexOf('Build/'))
    }
  }
  return model // 打印系统版本和手机型号
}

export const getDateDiff = (dateTimeStamp) => {
  var minute = 1000 * 60
  var hour = minute * 60
  var day = hour * 24
  // var halfamonth = day * 15
  var month = day * 30

  var now = new Date().getTime()
  var diffValue = now - dateTimeStamp * 1000

  if (diffValue < 0) {
    return
  }
  var monthC = diffValue / month
  var weekC = diffValue / (7 * day)
  var dayC = diffValue / day
  var hourC = diffValue / hour
  var minC = diffValue / minute
  let result = ''
  if (monthC >= 1) {
    result = '' + parseInt(monthC) + '月前'
  } else if (weekC >= 1) {
    result = '' + parseInt(weekC) + '周前'
  } else if (dayC >= 1) {
    result = '' + parseInt(dayC) + '天前'
  } else if (hourC >= 1) {
    result = '' + parseInt(hourC) + '小时前'
  } else if (minC >= 1) {
    result = '' + parseInt(minC) + '分钟前'
  } else {
    result = '刚刚'
  }

  return result
}

export const isAndroid = () => {
  const agent = navigator.userAgent
  return agent.indexOf('Android') > -1 || agent.indexOf('Adr') > -1
}

export const isIOS = () => {
  const agent = navigator.userAgent
  return !!agent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
}

export const isChrome = () => {
  return navigator.userAgent.indexOf('Chrome') !== -1
}

/**
 * 格式化剩余时间
 * @param {*} endtime
 * @param {*} splitChar[] (e.g. ['秒', '分', '小时', '天'])
 */
export const formatRestTime = (endtime, splitChar = []) => {
  var time = (parseInt(endtime) - new Date().getTime()) / 1000
  return formatRestFixedTime(time, splitChar)
}

export const formatRestFixedTime = (time, splitChar = []) => {
  var duration = formatCountDownTime(time)
  if (duration.length) {
    if (splitChar.length) {
      let text = ''
      for (let i = 0; i < duration.length; i++) {
        text = duration.pop() + splitChar[i] + text
      }
      return text
    }
    return duration.join(':')
  }
  return '结束'
}

export const formatCountDownTime = (time) => {
  var duration = []
  if (time > 0) {
    let day = Math.floor(time / 60 / 60 / 24)
    if (day > 0) {
      duration.push(day)
    }
    let hour = Math.floor((time / 60 / 60) % 24)
    if (duration.length || hour > 0) {
      duration.push(hour)
    }
    let minute = Math.floor((time / 60) % 60)
    if (duration.length || minute > 0) {
      duration.push(minute < 10 ? '0' + minute : minute)
    }
    let second = Math.floor(time % 60)
    if (duration.length || second > 0) {
      duration.push(second < 10 ? '0' + second : second)
    }
  }
  return duration
}

export const randomString = (length) => {
  let text = ''
  const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

  for (let i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length))
  }

  return text
}

export function getTimestamp () {
  const date = new Date()
  const timeString = Date.parse(date).toString()
  return timeString.slice(0, timeString.length - 3)
}

// 实际上就是新建一个iframe的生成器
export const createIframe = () => {
  var iframe
  return function () {
    if (iframe) {
      return iframe
    } else {
      iframe = document.createElement('iframe')
      iframe.style.display = 'none'
      document.body.appendChild(iframe)
      return iframe
    }
  }
}

export const openApp = (callback) => {
  const localUrl = 'youyue://open'
  if (isIOS() || (isAndroid() && isChrome())) {
    window.location.href = localUrl
  } else {
    const openIframe = createIframe()
    openIframe.src = localUrl
  }
  console.log('正在尝试打开APP', localUrl)
  setTimeout(function () {
    callback()
  }, 200)
}

/**
 * 格式化解析内容为JSON对象
 * @param {*} data
 */
export const formatParseJson = (data) => {
  if (typeof data === 'object' && data.constructor === Object) {
    return data
  } else {
    return JSON.parse(data)
  }
}
